package cn.caijiapeng.spt.model.base;

import java.util.List;

import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;

import cn.caijiapeng.spt.bean.Query;
import cn.caijiapeng.spt.kit.MyKit;

public abstract class BaseModel<M extends BaseModel<?>> extends Model<M>{
	private static final long serialVersionUID = 1553880991649909030L;
	
	
	@Override
	public boolean save() {
		try {
			set("create_time", MyKit.getCurCreateTime());
			set("refresh_time", MyKit.getCurRefreshTime());
		} catch (Exception e) {
		}
		return super.save();
	}
	
	@Override
	public boolean update() {
		try {
			set("refresh_time", MyKit.getCurRefreshTime());
		} catch (Exception e) {
		}
		return super.update();
	}
	
	/** 查找全部 */
	public List<M> getList() {
		return getList(new Query());
	}
	
	/** 查找全部 
	 * @param orderBy 排序 例如 id desc
	 **/
	public List<M> getList(String orderBy) {
		return getList(new Query(orderBy));
	}
	
	/** 查找全部 
	 * @param 排序 例如 id desc
	 * @param order 升序/降序*/
	public List<M> getList(Kv cond) {
		return getList(new Query(cond));
	}

	/** 查找全部 
	 * @param where 查询条件
	 * @param sort 排序字段
	 * @param order 升序/降序*/
	public List<M> getList(Query queryList) {
		Kv kv = Kv.by("table", getTableName());
		if(queryList.getCond() != null){
			kv.set("cond", queryList.getCond());
		}
		if(StrKit.notBlank(queryList.getOrderBy())){
			kv.set("orderBy", queryList.getOrderBy());
		}
		if(StrKit.notBlank(queryList.getColumns())){
			kv.set("columns", queryList.getColumns());
		}
		if(queryList.getLimit() != null){
			kv.set("limit", " limit " + queryList.getLimit());
		}
		return find(getSqlPara("public.list", kv));
	}
	
	public M getFirst(Kv cond) {
		return getFirst(new Query(cond));
	}
	
	public M getFirst(Query queryList) {
		List<M> list = getList(queryList);
		if(list == null || list.size() <= 0) {
			return null;
		}
		return list.get(0);
	}
	
	public String getTableName() {
		return _getTable().getName();
	}

}
